<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';
import LookVoucherPop from '@/pages/allOrder/lookVoucherPop.vue';
import PayMessagePop from '@/pages/allOrder/payMessagePop.vue';
import AfterSalePop from '@/pages/allOrder/afterSalePop.vue';
import consts from '@/consts.ts';
import {
  addAgainPost,
  cancelOrderPost,
  confirmReceiptPost,
  orderStatusGet,
  paymentVoucherPost,
  uploadPost,
} from '@/services/my.ts';
import type { OrderList } from '@/types/my.ts';
import type { UploaderFileListItem } from 'vant';

const $router = useRouter();
const $route = useRoute();
const orderList = ref<OrderList[]>([]);
const orderData = reactive({
  payMessage: {
    supplierName: '',
    bankAccount: '',
    depositBank: '',
    orderId: '',
    isChange: false, // 是否为更新凭证
  },
  form: {
    limit: 10,
    page: 1,
    status: $route.query.type ? ($route.query.type as string) : '',
  },
});

const onClickTab = () => {
  // 切换的时候重置数据
  orderList.value = [];
  orderData.form.page = 1;
  orderData.form.limit = 10;
  finished.value = false;
  loadData();
};

// 查看凭证
const lookVoucherPop = ref(false);
const lookVoucherImg = ref('');
const onLookVoucherClick = (props: any) => {
  lookVoucherImg.value = props.payProof;
  lookVoucherPop.value = true;
};
// 上传凭证
const upVoucherPop = ref(false);
const voucherImg = ref<UploaderFileListItem[]>([]);
const onUpVoucherClick = (props: any) => {
  // 清除数据
  voucherImg.value = [];
  orderData.payMessage.supplierName = props.supplierName;
  orderData.payMessage.bankAccount = props.bankAccount;
  orderData.payMessage.depositBank = props.depositBank;
  orderData.payMessage.orderId = props.orderId;
  orderData.payMessage.isChange = !!props.payProof;
  if (props.payProof) {
    voucherImg.value = props.payProof.split(',').map((item: any) => {
      return {
        url: item,
      };
    });
  }
  upVoucherPop.value = true;
};
const onVoucherSubClick = async () => {
  if (!voucherImg.value[0]?.url) {
    showToast('请上传凭证');
    return;
  }
  const { err, message } = await paymentVoucherPost({
    orderId: orderData.payMessage.orderId,
    payProof: voucherImg.value[0].url,
    isChange: orderData.payMessage.isChange,
  });
  if (err) {
    showToast(err);
    return;
  }
  upVoucherPop.value = false;
  await restFun();
  showToast(message);
};

// 上传图片处理
const beforeRead = (file: any) => {
  const isJPG =
    file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
  const isLt1M = file.size / 1024 / 1024 < 10;
  if (!isJPG) {
    showToast('只能上传jpg/png/jpeg文件!');
  }
  if (!isLt1M) {
    showToast('上传图片大小不能超过 10MB!');
  }
  return isJPG && isLt1M;
};
const afterRead = async (file: any) => {
  file.status = 'uploading';
  file.message = '上传中...';
  const formData = new FormData();
  formData.append('file', file.file);
  const { err, data } = await uploadPost(formData);
  if (err) {
    file.status = 'failed';
    file.message = '上传失败';
  } else {
    file.status = 'done';
    file.message = '上传成功';
    voucherImg.value = [{ url: data }];
  }
};

const payMessagePop = ref(false);
const onPayMessageClick = (props: any) => {
  orderData.payMessage.supplierName = props.supplierName;
  orderData.payMessage.bankAccount = props.bankAccount;
  orderData.payMessage.depositBank = props.depositBank;
  payMessagePop.value = true;
};

// 售后
const afterSalePop = ref(false);
const afterOrderId = ref('');
const onAfterClick = (props: any) => {
  afterSalePop.value = true;
  afterOrderId.value = props.orderId;
};

const onAfterDetailClick = (props: any) => {
  $router.push({
    path: '/afterSales',
    query: {
      orderId: props.orderId,
    },
  });
};
// 订单详情
const onImageClick = (props: any) => {
  $router.push({
    path: '/orderDetail',
    query: {
      orderId: props.orderId,
    },
  });
};
const onShopClick = (props: any) => {
  $router.push({
    path: '/store',
    query: {
      supplierId: props.supplierId,
    },
  });
};

const onCancelClick = async (props: any) => {
  const { err, message } = await cancelOrderPost({
    orderId: props.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  restFun();
  showToast(message);
};

const onAgainOrderClick = async (props: any) => {
  const { err } = await addAgainPost({
    orderId: props.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  $router.push({ path: '/car' });
};

const onConfirmShopClick = async (props: any) => {
  const { err, message } = await confirmReceiptPost({
    orderId: props.orderId,
  });
  if (err) {
    showToast(err);
    return;
  }
  await restFun();
  showToast(message);
};

// 重置函数
const restFun = async () => {
  orderList.value = [];
  orderData.form.page = 1;
  await loadData();
};

const loading = ref(false);
const finished = ref(false);
const loadData = async () => {
  try {
    loading.value = true;
    const { data, err } = await orderStatusGet(orderData.form);
    if (err) {
      showToast(err);
      return;
    }
    orderList.value = [...orderList.value, ...data.list];
    if (data.list.length < orderData.form.limit) {
      finished.value = true;
    } else {
      orderData.form.page += 1;
    }
  } catch (error: any) {
    showToast(error);
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="order-container">
    <van-tabs
      v-model:active="orderData.form.status"
      @click-tab="onClickTab"
      line-width="1.2em"
      color="#00BA9F"
      title-active-color="#00BA9F"
    >
      <van-tab
        v-for="(item, index) in consts.orderTabList"
        :key="index"
        :name="item.name"
        :title="item.label"
      >
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="loadData"
          v-if="orderList.length > 0"
        >
          <div class="order-box" v-for="order in orderList" :key="order.orderId">
            <div class="box-title">
              <div class="title-left" @click="onShopClick(order)">
                <svg-icon icon-class="shop" size="1.3em" />
                <div class="title-text">{{ order.supplierName }}</div>
                <svg-icon icon-class="right" size="1em" />
              </div>
              <div class="title-right">
                <template
                  v-if="order.afterSaleFlag === 'APPLY' || order.afterSaleFlag === 'AFTERSALEING'"
                >
                  售后中
                </template>
                <template v-else-if="order.afterSaleFlag === 'COMPLETED'"> 售后完成</template>
                <template v-else-if="order.afterSaleFlag === 'CANCELED'"> 售后已关闭</template>
                <template v-else>{{ (consts.orderStatus as any)[order.orderStatus] }}</template>
              </div>
            </div>
            <div
              class="goods_box"
              v-for="orderItem in order.orderGoodsList"
              :key="orderItem.goodsId"
            >
              <van-image
                @click="onImageClick(order)"
                :src="orderItem.goodsImg?.split(',')[0]"
                round
              />
              <div class="goods_spc" @click="onImageClick(order)">
                <div class="goods_name">{{ orderItem.goodsName }}</div>
                <div class="goods_level">{{ orderItem.goodsSpec }}</div>
              </div>
              <div class="goods_price">
                <div class="price_num curPrice">{{ `￥${orderItem.discountPrice}` }}</div>
                <div class="price_num disPrice">{{ `￥${orderItem.price}` }}</div>
                <div class="price_num amount">{{ `x ${orderItem.amount}` }}</div>
              </div>
            </div>
            <div class="state" v-if="order.trackingNumber">
              <div class="state-text">
                <template
                  v-if="order.afterSaleFlag === 'APPLY' || order.afterSaleFlag === 'AFTERSALEING'"
                >
                  售后中
                </template>
                <template v-else-if="order.afterSaleFlag === 'COMPLETED'"> 售后完成</template>
                <template v-else-if="order.afterSaleFlag === 'CANCELED'"> 售后已关闭</template>
                <template v-else>{{ (consts.orderStatus as any)[order.orderStatus] }}</template>
              </div>
              <div class="state-number">物流单号：{{ order.trackingNumber }}</div>
            </div>
            <div class="order-price">
              <div class="total-price">
                合计金额：
                <span>{{ `￥ ${order.orderPrice}` }}</span>
              </div>
              <div class="disPrice">
                <span>折后金额：</span>
                <span>￥</span>
                <span class="price-num">{{ `${order.orderReceivePrice}` }}</span>
              </div>
            </div>
            <div class="order-bottom">
              <!--
                按钮状态：
                    取消订单: 待支付 *
                    上传凭证: 待支付 *
                    再来一单：已取消 *
                    查看凭证：待发货 待收货 已完成 待收货 *
                    申请售后：待发货 待收货 *
                    售后详情：售后中
                    更换凭证：支付待审核 *
                    确认收货：待收货
              -->
              <van-button
                v-if="order.orderStatus === 'UNPAID'"
                @click="onCancelClick(order)"
                class="infoButton"
                text="取消订单"
              />
              <van-button
                v-if="order.orderStatus !== 'COMPLETED'"
                @click="onPayMessageClick(order)"
                class="infoButton"
                text="收款信息"
              />
              <van-button
                v-if="order.orderStatus === 'UNPAID'"
                @click="onUpVoucherClick(order)"
                class="colorButton"
                text="上传凭证"
              />
              <van-button
                class="colorButton"
                v-if="order.orderStatus === 'CANCELED' || order.orderStatus === 'COMPLETED'"
                @click="onAgainOrderClick(order)"
                text="再来一单"
              />
              <van-button
                v-if="['UNDELIVER', 'DELIVERED', 'COMPLETED', 'APPLY'].includes(order.orderStatus)"
                class="colorButton"
                @click="onLookVoucherClick(order)"
                text="查看凭证"
              />
              <van-button
                v-if="
                  (order.orderStatus === 'UNDELIVER' || order.orderStatus === 'DELIVERED') &&
                  (order.afterSaleFlag === 'NOT_APPLY' || order.afterSaleFlag === 'CANCELED')
                "
                @click="onAfterClick(order)"
                class="infoButton"
                text="申请售后"
              />
              <van-button
                v-if="['APPLY', 'AFTERSALEING', 'COMPLETED'].includes(order.afterSaleFlag)"
                class="infoButton"
                @click="onAfterDetailClick(order)"
                text="售后详情"
              />
              <van-button
                v-if="order.orderStatus === 'PAYAUDIT' || order.orderStatus === 'PAYREJECT'"
                @click="onUpVoucherClick(order)"
                class="infoButton"
                text="更换凭证"
              />
              <van-button
                v-if="
                  order.orderStatus === 'DELIVERED' &&
                  (order.afterSaleFlag === 'NOT_APPLY' ||
                    order.afterSaleFlag === 'COMPLETED' ||
                    order.afterSaleFlag === 'CANCELED')
                "
                @click="onConfirmShopClick(order)"
                class="colorButton"
                text="确认收货"
              />
            </div>
          </div>
        </van-list>
        <van-empty v-else description="暂无订单~" />
      </van-tab>
    </van-tabs>
  </div>
  <van-popup v-model:show="upVoucherPop" position="bottom" :style="{ maxHeight: '70%' }">
    <div class="voucher-popup some-popup">
      <div class="pay-text">收款信息</div>
      <div class="pay-icon">
        <svg-icon icon-class="shop" size="1.3em" />
        <span>{{ orderData.payMessage.supplierName }}</span>
      </div>
      <van-field
        class="custom-field"
        label="收款人"
        :model-value="orderData.payMessage.supplierName"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field
        class="custom-field"
        label="收款账户"
        :model-value="orderData.payMessage.depositBank"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field
        class="custom-field"
        label="收款银行"
        :model-value="orderData.payMessage.bankAccount"
        type="textarea"
        rows="1"
        autosize
        readonly
      />
      <van-field class="up-lable" label="上传凭证" placeholder="请上传凭证">
        <template #input>
          <van-uploader
            v-model="voucherImg"
            preview-size="5em"
            :before-read="beforeRead"
            :after-read="(file: any) => afterRead(file)"
            :max-count="1"
          >
            <template #default>
              <div class="upload-style">
                <svg-icon icon-class="uploader" size="1.4em" />
              </div>
            </template>
          </van-uploader>
        </template>
        <template #extra>
          <div class="upload-tip">只能上传jpg/png文件，且不超过10MB</div>
        </template>
      </van-field>
      <div class="voucher-bottom">
        <van-button color="#E89000" @click="upVoucherPop = false" plain round text="返回" />
        <van-button color="#E89000" @click="onVoucherSubClick" round text="提交" />
      </div>
    </div>
  </van-popup>

  <!-- 查看凭证 -->
  <LookVoucherPop v-model="lookVoucherPop" :look-voucher-img="lookVoucherImg" />
  <!-- 收款信息 -->
  <PayMessagePop v-model="payMessagePop" :payMessage="orderData.payMessage" />
  <!-- 售后 -->
  <AfterSalePop v-model="afterSalePop" :order-id="afterOrderId" />
</template>

<style scoped lang="scss">
.order-container {
  width: 100%;
  height: 100vh;
  background: #f6f6f6;

  :deep(.van-tabs__content) {
    background: #f6f6f6;
  }

  .order-box {
    width: 100%;
    background: white;
    padding: 0 16px 16px 16px;
    margin-top: 8px;

    .box-title {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title-left {
        display: flex;
        align-items: center;

        .title-text {
          font-size: 13px;
          font-weight: 500;
          margin-left: 8px;
          color: #222222;
        }
      }

      .title-right {
        font-size: 14px;
        font-weight: 400;
        color: #e86600;
      }
    }

    .goods_box {
      width: 100%;
      height: 104px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .van-image {
        width: 88px;
        height: 88px;
        border-radius: 8px;
      }

      .goods_spc {
        width: 170px;
        height: 100%;
        padding-top: 8px;

        .goods_name {
          width: 100%;
          font-size: 13px;
          font-weight: 500;
          color: #000000;
          // 超过一行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .goods_level {
          width: 100%;
          font-size: 12px;
          font-weight: 400;
          margin-top: 3px;
          color: #787878;
          // 超过三行就显示省略号
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .goods_price {
        height: 100%;
        padding-top: 8px;

        .price_num {
          display: flex;
          justify-content: flex-end;
        }

        .curPrice {
          font-size: 14px;
          font-weight: 500;
        }

        .disPrice {
          font-size: 12px;
          font-weight: 400;
          color: #aaaaaa;
          text-decoration: line-through;
        }

        .amount {
          font-size: 10px;
          font-weight: 400;
          color: #aaaaaa;
        }
      }
    }
  }

  .order-price {
    width: 100%;
    height: 24px;
    font-size: 12px;
    font-weight: 400;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .total-price {
      color: #787878;

      span {
        text-decoration: line-through;
      }
    }

    .disPrice {
      margin-left: 12px;
      color: #222222;

      .price-num {
        font-size: 16px;
        font-weight: 500;
        color: #222222;
      }
    }
  }

  .state {
    width: 100%;
    height: 40px;
    font-size: 14px;
    margin-bottom: 8px;
    padding: 0 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f6f6f6;

    .state-text {
      font-weight: 500;
      color: #222222;
    }

    .state-number {
      color: #00000080;
      font-weight: 400;
    }
  }

  .order-bottom {
    width: 100%;
    min-height: 36px;
    margin-top: 8px;
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;

    .infoButton {
      color: #454545;
      background: #f6f6f6;
    }

    .colorButton {
      color: #e86600;
      background: #e8900033;
    }

    .van-button {
      font-size: 12px;
      height: 36px;
      margin-left: 6px;
      padding: 0 10px;
      border-radius: 4px;
    }
  }
}

.some-popup {
  width: 100%;
  background: #ffffff;
  padding: 0 16px;

  .pay-text {
    width: 100%;
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
  }

  .pay-icon {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;

    span {
      margin-left: 8px;
      font-size: 13px;
      font-weight: 500;
      color: #000000;
    }
  }

  :deep(.van-field__control) {
    color: #222222;
    font-size: 13px;
    font-weight: 400;
  }

  :deep(.van-field__label) {
    color: #787878 !important;
    font-size: 13px;
    font-weight: 400;
  }
}

.voucher-popup {
  :deep(.van-button--normal) {
    width: 160px;
    height: 40px;
    margin: 20px 0;
  }

  //:deep(.van-uploader) {
  //  width: 64px;
  //  height: 64px;
  //}

  .up-lable {
    :deep(.van-field__label) {
      font-size: 14px;
      font-weight: 500;
      color: #222222;
    }
  }

  .upload-tip {
    font-size: 12px;
    font-weight: 400;
    color: #787878;
    margin-left: 92px;
  }

  .voucher-bottom {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
